import request from './index';

export const getProductList = (page: number, pageSize: number, productId?: string | number) => {
  return request.post(
    `http://localhost:9027/api-service-product/api/admin/product/list/${page}/${pageSize}`,
    productId ? { productId } : {}
  );
};

export const getProductDetail = (id: string) =>
  request.post('/api/app/product/queryOne', { id });

export const getRecommendProducts = (productId: string | number) => {
  return request.post('http://localhost:9027/api-service-product/api/admin/product/recommend', { productId });
};

// 新增商品
export const addProduct = (data: {
  name: string;
  price: number;
  desc: string;
  category: string;
  image: string;
}) => request.post('/api/app/product/add', data);

// 删除商品
export const deleteProduct = (id: number) =>
  request.post('/api/app/product/delete', { id });

// 更新商品
export const updateProduct = (params: any, file?: File) => {
  const formData = new FormData();
  Object.keys(params).forEach(key => {
    if (params[key] !== undefined && params[key] !== null && params[key] !== '') {
      formData.append(key, params[key]);
    }
  });
  if (file) {
    formData.append('file', file);
  }
  return request.post('http://localhost:9027/api-service-product/api/admin/product/update', formData);
};

// 上传商品图片
export const uploadProductImage = (file: File) => {
  const formData = new FormData();
  formData.append('file', file);
  return request.post('/api/app/product/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  });
};

export const createProduct = (params: any, file: File) => {
  const formData = new FormData();
  Object.keys(params).forEach(key => {
    if (params[key] !== undefined && params[key] !== null && params[key] !== '') {
      formData.append(key, params[key]);
    }
  });
  if (file) {
    formData.append('file', file);
  }
  return request.post('http://localhost:9027/api-service-product/api/admin/product/create', formData);
};

export const enableProduct = (id: number, flag: boolean) => {
  return request.post(`http://localhost:9027/api-service-product/api/admin/product/delete/${id}?flag=${flag}`);
};

export const searchProductById = (id: number) => {
  return request.post('http://localhost:9027/api-service-product/api/admin/product/queryOne', { id });
};

export const searchProductByName = (productName: string) => {
  return request.post('http://localhost:9027/api-service-product/api/admin/product/query?productName=' + productName);
}; 